<?php
class Article extends AppModel { 
       var $name = 'Article';
       
       var $article_content  = '';
        
       var $content_to_oss = true; //将内容保存到OSS

       var $hasOne = array(
          'ArticleContent'=>array(
            'className'     => 'ArticleContent',
           'foreignKey'    => 'id',
           //'conditions'    => array('ArticleContent.id = Article.id'),
           'dependent'=> true
          ),
        );

       var $hasMany = array(
	       'Uploadfile' => array(
		       'className'     => 'Uploadfile',
		       'foreignKey'    => 'data_id',
		       'conditions'    => array('Uploadfile.trash' => '0'), 
		       'order'    => 'Uploadfile.created ASC',
		       'limit'        => '',
		       'dependent'=> true
	       )
       ); 
       /* 
       var $belongsTo=array(
        'Category' => array(
            'className' => 'Category',
            'foreignKey' => 'cate_id',
        ),
    );
    */
    var $validate = array(
    	'name' => array(
            'rule' => 'notEmpty',
            'message' => 'This field cannot be left blank.',
        ),
    	/*'cate_id' => array(
    			'rule' => 'notEmpty',
    			'message' => 'This field cannot be left blank.',
    	),
        'slug' => array(
        	'notEmpty'=>array(
        		'rule' => 'notEmpty',
            	'message' => 'This field cannot be left blank.',
        	),
	        'isUnique'=>array(
	            'rule' => 'isUnique',
	            'message' => 'The value has already been taken.',
	        ),
        ),*/
    );
    

    public function beforeSave($options = array())
    {
    	parent::beforeSave($options);
    
    	$this->article_content = $this->data['Article']['content'] ?  $this->data['Article']['content'] : $this->data['ArticleContent']['content'];
    	$this->data['Article']['content'] = '';
    	$this->data['ArticleContent'] = '';
    	return true;
    }
    
    public function afterSave($created = false) {
    	parent::afterSave($created);
    
    	$id =  $this->id;
    	if($this->content_to_oss && $id && $this->article_content &&  $this->id){
    		App::uses('CrawlUtility', 'Utility');
    		CrawlUtility::saveToAliOss($this->article_content, '/article_content/'.$id,false,true);
    	}
    
    	return true;
    }
    
    public function afterFind($results, $primary = false) {
    
    	if( $this->content_to_oss ) {
    		App::uses('CrawlUtility', 'Utility');
    		try{
    			foreach($results as &$item) {
    				$content = CrawlUtility::getFromAliOss('/article_content/'.$item['Article']['id']);
    				if($content) {
    					$item['ArticleContent']['content'] = $content; // 有内容时，才使用值，否则使用数据库中的值。兼容数据库中已有的数据
    				}
    			}
    		}
    		catch(Exception $e){
    			return $results;
    		}
    	}
    	return $results;
    }
    
} 